#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/15 18:00
# @Author : 闫峰
# @File    : view.py
import datetime
import json
from urllib import parse
import random
import time
from flask import request, Response, jsonify, Request
from service.hub_schedule.v1_apis import HubScheduleApis
from utils.functions_control import get_uuid, now
from utils.handler_request_log import handler_request_log
from utils.model import RedisData, StatusTypes
from utils.mongodb_utils import MongoDBLink
from utils.redis_operations import RedisOperator
from utils.time_control import count_time

user = parse.quote_plus("viviu")
passwd = parse.quote_plus("viu@1234")
sit_charge_mock_data_modb = MongoDBLink(
    uri=f'mongodb://{user}:{passwd}@10.86.3.113:27017/?authSource=admin',
    dbname='sit_charge_mock_data', coll_name='sit_charge_mock_data')
redis_op = RedisOperator()


@count_time
def ScheduleService_Schedule0_HTTP_Handler():
    is_forward = True
    redis_data = None
    status_code = None
    request_path = request.path
    request_method = request.method
    value = redis_op.hgetall(request_path)
    if value:
        redis_data = RedisData(**value)
        if redis_data.status_type.value in [StatusTypes.Forwarded_500.value, StatusTypes.Forwarded.value,StatusTypes.NoSource.value,StatusTypes.ExistSource.value,StatusTypes.InnerErroe.value]:
            is_forward = False
    sit_base_url = "http://cg-sit-auto.yuntiancloud.com/sched-hub" + request_path
    if request_method in ["DELETE", "GET"]:
        request_json = None
    else:
        request_json = request.json
    resp_json = None
    response = None
    if is_forward:

        if redis_data:
            if redis_data.time_count != "0":
                time.sleep(int(redis_data.timeout))
                time_count = int(redis_data.time_count) - 1
                redis_op.hset(name=request_path, key="time_count", value=time_count)
        status_code, resp_json = HubScheduleApis.hub_schedule_handler(sit_base_url, request_json)
        response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    else:
        if redis_data:
            if redis_data.status_type.value == StatusTypes.Forwarded_500.value:
                if redis_data.error_count != "0":

                    status_code = random.choice([500])
                    match status_code:
                        case 500:
                            resp_json = {
                                "ret": {
                                    "code": status_code,
                                    "reason": f"{request_path}调用失败",
                                    "msg": f"{request_path}调用失败",
                                    "request_id": str(get_uuid()),
                                }
                            }
                            resp_str = json.dumps(resp_json)
                            response = Response(resp_str, status=status_code, mimetype='application/json')
                    error_count = int(redis_data.error_count) - 1
                    redis_op.hset(name=request_path, key="error_count", value=error_count)
                elif redis_data.error_count == "0":
                    status_code, resp_json = HubScheduleApis.hub_schedule_handler(sit_base_url, request_json)
                    response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
            elif redis_data.status_type.value == StatusTypes.NoSource.value:
                if redis_data.error_count != "0":
                    resp_json = {
                        "ret": {
                            "code": 1,
                            "reason": f"",
                            "msg": f"no resource"
                        }
                    }
                    resp_str = json.dumps(resp_json)
                    response = Response(resp_str, status=status_code, mimetype='application/json')
                    error_count = int(redis_data.error_count) - 1
                    redis_op.hset(name=request_path, key="error_count", value=error_count)
                elif redis_data.error_count == "0":
                    status_code, resp_json = HubScheduleApis.hub_schedule_handler(sit_base_url, request_json)
                    response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
            elif redis_data.status_type.value == StatusTypes.ExistSource.value:
                if redis_data.error_count != "0":
                    resp_json = {
                        "ret": {
                            "code": 2,
                            "reason": f"",
                            "msg": f"no resource"
                        }
                    }
                    resp_str = json.dumps(resp_json)
                    response = Response(resp_str, status=status_code, mimetype='application/json')
                    error_count = int(redis_data.error_count) - 1
                    redis_op.hset(name=request_path, key="error_count", value=error_count)
                elif redis_data.error_count == "0":
                    status_code, resp_json = HubScheduleApis.hub_schedule_handler(sit_base_url, request_json)
                    response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
            elif redis_data.status_type.value == StatusTypes.InnerErroe.value:
                if redis_data.error_count != "0":
                    resp_json = {
                        "ret": {
                            "code": 3,
                            "reason": f"",
                            "msg": f"no resource"
                        }
                    }
                    resp_str = json.dumps(resp_json)
                    response = Response(resp_str, status=status_code, mimetype='application/json')
                    error_count = int(redis_data.error_count) - 1
                    redis_op.hset(name=request_path, key="error_count", value=error_count)
                elif redis_data.error_count == "0":
                    status_code, resp_json = HubScheduleApis.hub_schedule_handler(sit_base_url, request_json)
                    response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    handler_request_log(request, status_code, resp_json, sit_charge_mock_data_modb, True)
    return response


@count_time
def ScheduleService_release():
    is_forward = True
    redis_data = None
    status_code = None
    request_path = request.path
    request_method = request.method
    value = redis_op.hgetall(request_path)
    if value:
        redis_data = RedisData(**value)
        if redis_data.status_type.value in [StatusTypes.Forwarded_500.value, StatusTypes.Forwarded.value]:
            is_forward = False
    sit_base_url = "http://cg-sit-auto.yuntiancloud.com/sched-hub" + request_path
    if request_method in ["DELETE", "GET"]:
        request_json = None
    else:
        request_json = request.json
    resp_json = None
    response = None
    if is_forward:
        if redis_data:
            if redis_data.time_count != "0":
                time.sleep(int(redis_data.timeout))
                time_count = int(redis_data.time_count) - 1
                redis_op.hset(name=request_path, key="time_count", value=time_count)
        status_code, resp_json = HubScheduleApis.hub_schedule_handler(sit_base_url, request_json)
        response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    else:
        if redis_data:
            if redis_data.status_type.value == StatusTypes.Forwarded_500.value:

                status_code = random.choice([500])
                match status_code:
                    case 500:
                        resp_json = {
                            "ret": {
                                "code": status_code,
                                "reason": f"{request_path}调用失败",
                                "msg": f"{request_path}调用失败",
                                "request_id": str(get_uuid()),
                            }
                        }
                        resp_str = json.dumps(resp_json)
                        response = Response(resp_str, status=status_code, mimetype='application/json')
            elif redis_data.status_type.value == StatusTypes.Forwarded.value:
                pass
    handler_request_log(request, status_code, resp_json, sit_charge_mock_data_modb, True)
    return response
